<?
class ProductInfoException extends Exception{
}
/**
 *产品信息类.
 *获取产品信息.
 */
class ProductInfo{
	
	/**
	 *产品表ID.
	 *@var int
	 */
	public $pid;
	
	/**
	 *供应商ID.
	 *@var int
	 */
	public $aid;
	
	/**
	 *产品信息键值数组.
	 *@var array
	 */
	public $p_info;
	
	/**
	 *票付通内部接口对象
	 *@var object
	 */
	public $s;
	
	/**
	 *产品类型键值数组
	 *@static
	 *@var array
	 */
	public static $ptype=array("A"=>"景点","B"=>"线路","C"=>"酒店","D"=>"商品","F"=>"套票","G"=>'餐饮');


	/**
	 *构造函数.
	 *@param object $s 票付通内部接口对象
	 *@param int $pid 产品ID
	 *@param int $aid 供应商ID,直属供应产品按默认值，转供应产品需传
	 */
	public function __construct($s,$pid,$aid=0){
		$this->s=$s;
		$this->pid=$pid;
		$this->aid=$aid;
		if($aid){
			/*传入上级供应商ID和原始供应商ID比较，直属供应商aid=0*/
			$str="select apply_did from uu_products where id=$pid LIMIT 1";
			$GLOBALS['le']->query($str);
			$GLOBALS['le']->fetch_assoc();
			if($GLOBALS['le']->f("apply_did")==$aid) $this->aid=0;
		}
	}
	
	/**
	 *产品价格库存信息查询函数.
	 *从接口返回的价格和库存配置xml，得出产品价格库存,存在键值数组中
	 *@param object $simplexml simplexml对象
	 *@param date $begintime 开始时间
	 *@param date $endtime 结束时间
	 *@uses ProductInfo::getMinValidTime
	 *@uses ProductInfo::getMaxValidTime
	 *@return array 
	 */
	public function  getDatePrice($simplexml,$beginDate=null,$endDate=null){
		$array=array();
		$sorts=array();
		foreach($simplexml as $xml){	
			$weekdays=$xml->UUweekdays;
			$weekdays=explode(",",$weekdays);
			//平日价，周末价，节日价记录
			$days=(strtotime((string)$xml->UUend_date)-strtotime($xml->UUstart_date))/3600/24;
			$begintime=strtotime($xml->UUstart_date);
			for($i=0;$i<$days+1;$i++){
				$time=$begintime+$i*24*3600;
				$w=date("w",$time);
				$date=date("Y-m-d",$time);
				if($beginDate&&$date<$beginDate) continue;//非指定日期内
				if($endDate&&$date>$endDate) continue;//非指定日期内
				if(!isset($array[$date])){
					if($xml->UUptype==0){
						if(in_array($w,$weekdays)){
							$array[$date]=array(
                                "sprice"=>(string)$xml->UUn_price,
                                "lprice"=>(string)$xml->UUl_price,
                                "storage"=>(string)$xml->UUstorage
                            );
							$sorts[]=$date;
						}
					}elseif($xml->UUptype==1){//节假日
						$array[$date]=array("sprice"=>(string)$xml->UUs_price,"lprice"=>(string)$xml->UUl_price,"uid"=>(string)$xml->UUid,"storage"=>(string)$xml->UUstorage);
						$sorts[]=$date;
					}
				}elseif($xml->UUptype==1){
					$array[$date]=array("sprice"=>(string)$xml->UUs_price,"lprice"=>(string)$xml->UUl_price,"uid"=>(string)$xml->UUid,"storage"=>(string)$xml->UUstorage);
				}
			}
		}
		array_multisort($sorts,SORT_ASC,SORT_STRING,$array);
		return $array;
	}
	
	/**
	 *返回产品最小有效价格日期函数.
	 *从传入的时间得出最小有效日期，默认从当前日期加产品预订提前天数，-1表示无有效日期
	 *@param date $begintime 启用日期
	 *@return date|-1
	 */
	public function getMinValidTime($begintime=null){
		$pid=$this->pid;
		$validTime=-1;
		$str="select t.ddays,f.dhour from uu_products p join uu_jq_ticket t on t.pid=p.id left join uu_land_f f on f.pid=p.id where p.id=$pid limit 1";
		$GLOBALS['le']->query($str);
		$p_info=$GLOBALS['le']->fetch_assoc();
		// $mintime=date("Y-m-d",time()+3600*24*$p_info['ddays']);
		// if($mintime==date("Y-m-d")&&date("H:i:s")>$p_info['dhour']){
			// $mintime=date("Y-m-d",strtotime($mintime)+3600*24);
		// }
		$ddays = $p_info['ddays'];
		if(strtotime(date('Y-m-d H:i:s'))>strtotime(date('Y-m-d '.$p_info['dhour']))) $ddays+=1;
		$mintime=date("Y-m-d",time()+3600*24*$ddays);

		$begintime=($begintime===null)?$mintime:$begintime;
		$pri_xml=$this->s->get_Dynamic_Price_Merge($pid,"",0,$begintime);
		if($pri_xml==105){
		}elseif(is_numeric($pri_xml)){
			exit($pri_xml);
		}else{
			$pri_xml=simplexml_load_string($pri_xml);
			$array=$this->getDatePrice($pri_xml,$begintime);
			foreach($array as $date=>$price){
				$validTime=$date;
				break;
			}
		}
		return $validTime;
	}
	
	/**
	 *返回产品最大有效价格日期函数.
	 *从传入的时间得出最大有效日期，默认为空
	 *@param date $endtime 截止日期
	 *@return date|-1
	 */
	public function getMaxValidTime($endtime=""){
		$validTime=-1;
		$begintime=date("Y-m-d");
		/*传入日期小于当天，以当天为准*/
		if($endtime&&$endtime<$begintime) $endtime=$begintime;
		$pri_xml=$this->s->get_Dynamic_Price_Merge($this->pid,"",0,$begintime,$endtime);
		if($pri_xml==105){
		}elseif(is_numeric($pri_xml)){
			exit($pri_xml);
		}else{
			$pri_xml=simplexml_load_string($pri_xml);
			$array=$this->getDatePrice($pri_xml,$begintime,$endtime);
			foreach($array as $date=>$price){
				if($date>$validTime){
					$validTime=$date;
				}
			}
		}
		return $validTime;
	}
	
	/**
	 *返回时间段价格库存信息.
	 *@param date $beginDate 开始时间
	 *@param date $endDate 介绍时间
	 *@return array 
	 */
	public function getPeriodPrice($beginDate,$endDate, $ac, $ptype, $aid){
		if($endDate<$beginDate){
			$endDate=date("Y-m-d",strtotime($beginDate)+3600*24*100);
		}
//		$xml=$this->s->get_Dynamic_Price_Merge($this->pid,"",0);//get_Dynamic_Price_Merge


     	$xml = $this->s->Dynamic_Price_And_Storage($ac, $this->pid,"",3, $ptype, '' ,$aid, "$beginDate", "$endDate");

        $simplexml=simplexml_load_string($xml);
		$array=$this->getDatePrice($simplexml,$beginDate,$endDate);
//        if ($_SESSION['account']==100014 || $_SESSION['account']==100011) {
//            echo "$ac, $this->pid,$beginDate,3, $ptype, 0 ,$aid, $beginDate, $endDate";
////            print_r($array);
//            echo $xml;
//        }
		return $array;
	}
	
	/**
	 *返回产品信息.
	 * @param $s_pid int
	 *@return array
	 */
	public function pInfo($s_pid=null){
		if($this->p_info && !$s_pid){
			return $this->p_info;
		}
        $s_pid=$s_pid?$s_pid:$this->pid;
        $array=array();
		$str="select p.id as pid,p.apply_limit,p.salerid,p.p_status,".
            "p.apply_did,l.id as lid,l.title as ltitle,l.fax,l.attribute,".
            "l.p_type,l.jdjj,l.jqts,l.imgpath,t.id as tid,t.tprice,t.pay,t.reb,t.reb_type,".
            "t.title as ttitle,t.delaydays,t.ddays,t.buy_limit_low,t.sync_id,t.sync_status,t.overdue_refund,".
            "t.buy_limit_up,t.status,t.storage_open,t.storage,t.getaddr,t.notes,t.order_start,t.order_end,".
            "f.dhour,f.series_model,f.mdays,f.v_time_limit,f.tourist_info,f.sendVoucher,t.order_limit,f.tourist_info,f.ass_station,f.zone_id,l.venus_id 
             from uu_products p ".
            "left join uu_jq_ticket t on p.id=t.pid ".
            "left join uu_land l on p.contact_id=l.id ".
            "left join uu_land_f f on p.id=f.pid ".
            "where p.id=".$s_pid." limit 1";
		$GLOBALS['le']->query($str);
		$this->p_info=$GLOBALS['le']->fetch_assoc();
		$this->p_info['sapply_did']=($this->aid==0)?$this->p_info['apply_did']:$this->aid;
		return $this->p_info;
	}
	
	/**
	 *返回产品价格.
	 *@param int $did 分销商ID
	 *@param date $date 预订日期
	 *@param int $sale 是否零售
	 *@return int 
	 */
    public function tPrice($did, $date,$sale=0,$p_pid=NULL){
        if($sale==1)
            return $this->uPrice($did,$date,$p_pid);
        else
            return $this->jsPrice($did,$date,$p_pid);
    }
	
	/**
	 *返回产品分销价.
	 *@param int $did 分销商ID
	 *@param date $date 预订日期
	 *@return int 
	 */
//	public function jsPrice($did,$date){
//		$jsprice=$this->s->get_Dynamic_Price_Merge($this->pid,$date,1);
//		if($jsPrice==-1)
//			throw new ProductInfoException("产品$pid $date 结算价未设置");
//		$dprice=$this->dprice($did);
//		$jsprice=($dprice+$jsprice);
//		return $jsprice;
//	}
    public function jsPrice($did, $date,$p_pid=NULL){
        $p_pid=$p_pid?$p_pid:$this->pid;
        $jsprice=$this->s->get_Dynamic_Price_Merge($p_pid,$date,1);
        if($jsprice==-1)
            throw new ProductInfoException("产品$p_pid $date 结算价未设置");
        $dprice=$this->dprice($did,$p_pid);
        // echo $dprice;
        // exit;
        $jsprice=($dprice+$jsprice);
        return $jsprice;
    }
    /**
	 *返回产品价格.
	 *@param int $did 分销商ID
	 *@param date $date 预订日期
	 *@param int $sale 是否零售
	 *@return int 
	 */
    public function tPrice_n($sale, $date, $aid=NULL, $pid=NULL, $account=NULL){

        if ($sale==1) {
            return $this->uPrice_n($date, $pid, $aid, $account);
        }
        $pri = $this->jsPrice_n($date, $pid, $aid, $account);
        if (is_array($pri)) {
            $pri = $this->uPrice_n($date, $pid, $aid, $account);
        }
        return $pri;
//        return ($sale==1)?
//        $this->uPrice_n($date, $pid, $aid, $account):$this->jsPrice_n($date, $pid, $aid, $account);
    }
	/**
	 *使用新接口获取结算价
	 *@param date $date 预订日期
	 *@param int $pid 产品ID
	 *@param int $aid 上级供应商ID
	 *@param string $account 分销商账号 6 位
	 *@return int 
	 */
    public function jsPrice_n($date, $pid=NULL, $aid=NULL, $account=NULL){
        $pid = $pid ? $pid : $this->pid;
        $aid = $aid ? $aid : $this->aid;
        if($_SESSION['saccount']){
            $account = $account ? $account:$_SESSION['saccount'];
        }else{
            $account = $account ? $account:$_SESSION['account'];
        }
        // exit("Dynamic_Price_And_Storage($account,$pid,$date,1,0,0,$aid)");
        $xml = $this->s->Dynamic_Price_And_Storage($account,$pid,$date,1,0,0,$aid);
        if($xml==105 || $xml==1065){
            return array('status'=>'fail', 'msg'=>"产品$pid $date ($account,$aid,$xml)结算价未设置");
//            throw new ProductInfoException("产品$pid $date 结算价未设置");
        }else{
            $object = simplexml_load_string($xml);
            $jsprice=(string)$object->Rec->UUsprice;
        }
        return $jsprice;
    }
    
	/**
	 *使用新接口返回产品零售价.
	 *@param date $date 预订日期
	 *@param int $pid 产品ID
	 *@param int $aid 上级供应商ID
	 *@param string $account 分销商账号 6 位
	 *@return int 
	 */
    public function uPrice_n($date, $pid=NULL, $aid=NULL, $account=NULL){
        $pid = $pid ? $pid : $this->pid;
        $aid = $aid ? $aid : $this->aid;
//        if($_SESSION['saccount']){
//
//        }else{
//            $account = $account ? $account:$_SESSION['account'];
//        }
        $account = $account ? $account:$_SESSION['saccount'];
        $xml = $this->s->Dynamic_Price_And_Storage($account,$pid,$date,1,1,0,$aid);
        if($xml==105 || $xml==1065){
            return array('status'=>'fail', 'msg'=>"产品$pid $date 零售价未设置($xml)");
//            throw new ProductInfoException("产品$pid $date 零售价未设置");
        }else{
            $object = simplexml_load_string($xml);
            $uprice= (string)$object->Rec->UUsprice;
        }
        return $uprice;
    }
    
	/**
	 *返回产品零售价.
	 *@param int $did 分销商ID
	 *@param date $date 预订日期
	 *@return int 
	 */
    public function uPrice($did,$date,$p_pid=NULL){
        $p_pid=$p_pid?$p_pid:$this->pid;
        //$uprice=$this->s->get_Dynamic_Price_Merge($p_pid,$date,1,"","",1);
        $xml = $this->s->Dynamic_Price_And_Storage('',$p_pid,$date,1,1);
        if($xml==105)
            throw new ProductInfoException("产品$p_pid $date 零售价未设置");
        return (int)simplexml_load_string($xml)->Rec->UUsprice;
//        return $uprice;
    }
//	public function uPrice($did,$date){
//
//		$uprice=$this->s->get_Dynamic_Price_Merge($this->pid,$date,1,"","",1);
//		if($uprice==-1)
//			throw new ProductInfoException("产品$pid $date 零售价未设置");
//		return $uprice;
//	}
	
	/**
	 *返回产品零售价.
	 *@param int $did 分销商ID
	 *@param date $date 预订日期
	 *@return int 
	 */
	public function dprice($did, $pid=0){
		$pid= $pid > 0 ? $pid : $this->pid;
		$aid=$this->aid;
		$str="select dprice from uu_priceset where tid=$pid and pid=$did and aid=$aid";
		$GLOBALS['le']->query($str);
		$GLOBALS['le']->fetch_assoc();
		$dprice=abs($GLOBALS['le']->f('dprice'));
//        if ($_SESSION['account']==200566) {
//            echo '$dprice=' . $dprice, '$this->pid=' . $this->pid . '$this->aid=' . $this->aid;
//        }
		if($aid!=0){//二手供应产品
			$str="select aids from pft_p_apply_evolute where pid=$pid and fid=$did and sid=$aid";
			$GLOBALS['le']->query($str);
			$GLOBALS['le']->fetch_assoc();
			$aids=$GLOBALS['le']->f("aids");
            if ($aids) {
                $str = "select * from uu_priceset where pid in ($aids)";
                $GLOBALS['le']->query($str);
                while ($row = $GLOBALS['le']->fetch_assoc()) {
                    $dprices2[$row['tid'] . "_" . $row['pid'] . "_" . $row['aid']] = $row['dprice'];
                }
                $aids = explode(",", $aids);
                $aids[0] = 0;
                $count = count($aids);
                for ($i = 1; $i < $count; $i++) {
                    $dprice = $dprice + $dprices2[$pid . "_" . $aids[$i] . "_" . $aids[$i - 1]];
                }
            }
		}
		return $dprice;
	}
    public function dpriceBeta($did, $aid=0){
        $pid = $this->pid;
        $aid = $aid>0 ? $aid : $this->aid;
        $str="select dprice from uu_priceset  where tid=$pid and pid=$did and aid=$aid";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $dprice=abs($GLOBALS['le']->f('dprice'));
        if($aid!=0){//二手供应产品
            $str="select aids from pft_p_apply_evolute where pid=$pid and fid=$did and sid=$aid";
//            echo $str;
            $GLOBALS['le']->query($str);
            $row = $GLOBALS['le']->fetch_assoc();
            $aids=$GLOBALS['le']->f("aids");
            $str="select * from uu_priceset where pid in ($aids)";
            $GLOBALS['le']->query($str);
            while($row=$GLOBALS['le']->fetch_assoc()){
                $dprices2[$row['tid']."_".$row['pid']."_".$row['aid']]=$row['dprice'];
            }
            $aids=explode(",",$aids);
            $aids[0]=0;
            $count=count($aids);
            for($i=1;$i<$count;$i++){
                $dprice=$dprice+$dprices2[$pid."_".$aids[$i]."_".$aids[$i-1]];
            }
        }
        return $dprice;
    }
	/**
	 *返回产品指定日期库存.
	 *@param date $date 预订日期
	 *@return int  
	 */
	public function dayStorage($date){
		$storage=-1;
		$p_info=$this->pInfo();
		$pstorage=$this->s->get_Dynamic_Price_Merge($p_info['pid'],substr($date,0,10),1,"","",0,1);
		$pstorage=explode(",",$pstorage);
		$pstorage=$pstorage[1];//设置的日库存
		if($pstorage!=-1){
			$storageXml=$this->s->Dynamic_Storage_Check($p_info['tid'],1,$date);
			$storageXml=simplexml_load_string($storageXml);
			$storageXml=(string)$storageXml->Rec->UUXstr;
			$dayStorage=explode("|",$storageXml);
			$dayStorage=$dayStorage[1];//使用的日库存
			$storage=$pstorage-$dayStorage;
		}
		if($p_info['storage']!=-1){
			$storageXml=$this->s->Dynamic_Storage_Check($p_info['tid'],2,NUll,$p_info['storage_open']);
			$storageXml=simplexml_load_string($storageXml);
			$useStorage=$storageXml->Rec->UUXstr;
			$totalStorage=$p_info['storage']-$useStorage;//剩余总库存
			if(($totalStorage<$storage&&$storage>0)||$storage==-1) $storage=$totalStorage;
		}
		if($storage==-1) $storage="不限";
		return $storage;
	}
	
    /**
     * 产品供应查看函数,查看产品是否供应供应给该分销商
     *
     * @param $did  分销商ID
     * @param int $sid 上级供应商id
     * @return bool
     */
    public function supply($did){

		$apply_did = $this->GetApplyDid();
		//自身供应的产品
		if($apply_did==$did) return true;
		$str="SELECT id,pids FROM pft_product_sale_list WHERE fid=$did AND aid=$apply_did LIMIT 1";
//        echo $str;
		$GLOBALS['le']->query($str);
		if($GLOBALS['le']->fetch_assoc()){
			$pids=$GLOBALS['le']->f("pids");
            $sale_list_id = $GLOBALS['le']->f('id');
			if($pids=="A") return true;
			if(in_array($this->pid,explode(",", $pids))) return true;
		}

		//二手转供应的产品
		$str="SELECT id FROM pft_p_apply_evolute WHERE pid={$this->pid} AND sid={$this->aid} AND fid=$did AND status=0 LIMIT 1";
        if ($_SESSION['memberID']==81) {
            echo $str;exit;
        }

		$GLOBALS['le']->query($str);
		if($GLOBALS['le']->fetch_assoc()) return true;
//        return false;
//        if ($did==94) {
//            echo $did,',', $this->aid,',',$apply_did,',',$sale_list_id;
//        }
//        if ($did==469) {
//            echo $did,',', $this->aid,',',$apply_did,',',$sale_list_id;
////            469,66,1231
//        }
//        if ($did==94 || $did==22132) {
//            echo $str;
//            echo $did,',', $this->aid,',',$apply_did,',',$sale_list_id;
//            return $this->LetMeBuy($did, $apply_did,$sale_list_id);
//        }
		return false;
	}

    public function GetApplyDid($pid=0) {
        $pid = $pid ? $pid : $this->pid;
        $str="SELECT apply_did FROM uu_products WHERE id={$pid} LIMIT 1";
//        echo $str;
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        return $GLOBALS['le']->f("apply_did");
    }

    public function ChkEvolute($pid, $fid, $sid=0, $debug=false, $status=null)
    {
        $sql_get = "SELECT id,aids,sid,sourceid,lvl,status,active FROM pft_p_apply_evolute WHERE pid=$pid AND fid=$fid";
        if ($sid>0) {
            $sql_get .= " AND sid=$sid";
        }
        if (!is_null($status)) {
            $sql_get .= " AND status=$status";
        }
        $sql_get .= " LIMIT 1";
        if ($debug) {
            echo $sql_get;
        }
        $GLOBALS['le']->query($sql_get);
        return $GLOBALS['le']->fetch_assoc();
    }

    public function AddEvolute($pid, $fid, $sid, $sourceId, $aids, $lvl, $active)
    {
        $sql=<<<SQL
insert into pft_p_apply_evolute set pid={$pid},fid=$fid,sid={$sid},
sourceid=$sourceId,aids='$aids',lvl=$lvl,active=$active,rectime=now()
SQL;
//        echo $sql;
        $GLOBALS['le']->query($sql);
    }
    /**
     * 让分销商可以购买其他供应商的产品,建立供销关系，设置产品销售权限
     *
     * @param $did 分销商id
     * @param $apply_did 原始供应商id
     * @param int $sale_list_id  销售权限列表id
     * @return bool
     */
    /**
	 *产品供应是否在售.
	 *查看产品是否在售，非在售产品抛出异常
	 *@throws ProductInfoException
	 */
	public function saleCheck(){
		$p_info=$this->pInfo();
		$pid=$p_info['pid'];
		if($p_info['apply_limit']!=1)
			throw new ProductInfoException("产品 $pid 未通过审核");
		if($p_info['p_status']!=0&&$p_info['p_status']!=3&&$p_info['p_status']!=4&&$p_info['p_status']!=5)
			throw new ProductInfoException("无发分销该产品");
	}

    /**
     * @param $did 下单人id
     * @param int $a_did 上级的上级供应商id
     * @param int $apply_did 原始供应商id
     * @param bool $debug
     * @param int $s_aid 上级供应商id
     * @return bool
     */
    public function LetMeBuy($did, $a_did=0, $apply_did=0,$debug=false, $s_aid=0, $pid=0)
    {
        if (!$apply_did) {
            $apply_did = $this->GetApplyDid();
        }
        if (!$pid) {
            $pid = $this->pid;
        }
        //TODO::判断是否已经建立关系
        $sql_chk = "SELECT id FROM pft_member_relationship WHERE parent_id={$s_aid} AND son_id=$did AND ship_type=0 LIMIT 1";
        if ($debug) {
            echo $sql_chk;
        }
        $GLOBALS['le']->query($sql_chk);
        if (!$GLOBALS['le']->fetch_assoc()) {
            $sql_ins = "INSERT INTO pft_member_relationship(parent_id,son_id,son_id_type,ship_type,rectime) VALUES({$s_aid}, $did,0,0,now())";
            if ($debug) echo $sql_ins;
            $GLOBALS['le']->query($sql_ins);
        }
        //直销
        if ($apply_did == $s_aid)
        {
            return $this->OneHandConf($pid, $did, $s_aid);
        }
        //没有权限购买的产品，在产品进化表写入一条数据
        if ($s_aid!=$a_did) {
            // 一手--from Tongbao Chun
            $check_sql="select pids from pft_product_sale_list where fid={$s_aid} and aid={$a_did} limit 1";
            if ($debug) echo $check_sql;
            $GLOBALS['le']->query($check_sql);
            $GLOBALS['le']->fetch_assoc();
            $pids = $GLOBALS['le']->f('pids');
            if($pids) $pids = explode(',',$pids);
            if ( $pids && in_array($pid, $pids) ) {
                //一级转供应
                $tmp = $this->ChkEvolute($pid, $s_aid, $a_did,  $debug);
                if (!$tmp) {
                    $this->AddEvolute($pid, $s_aid, $a_did, $a_did, $a_did, 1, 1);
                } elseif( $tmp && $tmp['status'] == 1) {
                    // 新转换的分销商已经权限
                    $upd_sql="update pft_p_apply_evolute set status=0 where id={$tmp['id']} limit 1";
                    $GLOBALS['le']->query($upd_sql);
                }
                //二级转供应
                $tmp = $this->ChkEvolute($pid, $did, $s_aid, $debug);
                if (!$tmp) {
                    $this->AddEvolute($pid, $did, $s_aid, $a_did, "{$a_did},{$s_aid}", 2, 0);
                }
                elseif ($tmp && $tmp['status']==1) {
                    $upd_sql="update pft_p_apply_evolute set status=0 where id={$tmp['id']} limit 1";
                    $GLOBALS['le']->query($upd_sql);
                }
            }
            else {
                // 以下都是二手供应
                $db_data = $this->ChkEvolute($pid, $s_aid, $a_did, $debug, 0);
                if($db_data){
                    $id = $db_data['id'];
                    if($db_data['active']==0){
                        // 开启转供应
                        $upd_sql="update pft_p_apply_evolute set active=1 where id={$db_data['id']} limit 1";
                        // echo $upd_sql;
                        $GLOBALS['le']->query($upd_sql);
                    }
                    $tmp = $this->ChkEvolute($pid, $did, $s_aid, $debug );
                    if (!$tmp) {
                        $aids_n  = $db_data['aids'].",$s_aid";
                        $lvl_n   = $db_data['lvl']+1;
                        $this->AddEvolute($pid, $did, $s_aid, $apply_did, "{$aids_n}", $lvl_n, 0);
                    } elseif( $tmp && $tmp['status'] == 1){
                        $upd_sql="update pft_p_apply_evolute set status=0 where id={$tmp['id']} limit 1";
                        $GLOBALS['le']->query($upd_sql);
                    }
                }
            }
        }
        else {
            $this->OneHandConf($pid, $did, $apply_did);
        }
        return true;
    }

    private function OneHandConf($pid, $did, $apply_did)
    {
        //直销
        $str="SELECT id,pids FROM pft_product_sale_list WHERE fid=$did AND aid=$apply_did LIMIT 1";
        $GLOBALS['le']->query($str);
        if(!$GLOBALS['le']->fetch_assoc()){
            $sql = "INSERT INTO pft_product_sale_list SET pids='A',fid=$did,aid=$apply_did";
        }
        else {
            $sale_list_id = $GLOBALS['le']->f('id');
            $pids = $GLOBALS['le']->f('pids');
            if ($pids == 'A') {
                return true;
            }
            $sql = "UPDATE pft_product_sale_list SET pids=CONCAT(`pids`,',', {$pid}) WHERE id=$sale_list_id LIMIT 1";
        }
        $GLOBALS['le']->query($sql);
    }

}
?>